# Copyright (c) 2025 Huawei Technologies Co. Ltd.
# deepinsight is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#          http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.
import uuid

from starlette import status
from starlette.exceptions import HTTPException
from starlette.requests import HTTPConnection

from deepinsight.service.auth.openeuler_intelligence.session_manager import SessionManager


class UserHTTPException(HTTPException):
    def __init__(self, status_code: int, retcode: int, rtmsg: str, data):
        super().__init__(status_code=status_code)
        self.retcode = retcode
        self.rtmsg = rtmsg
        self.data = data


async def verify_user(request: HTTPConnection):
    """验证用户是否在Session中"""
    try:
        session_id = None
        auth_header = request.headers.get("Authorization")
        if auth_header and auth_header.startswith("Bearer "):
            session_id = auth_header.split(" ", 1)[1]
        elif "ECSESSION" in request.cookies:
            session_id = request.cookies["ECSESSION"]
        if session_id is None:
            raise UserHTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
                                    retcode=401, rtmsg="Authentication Error.", data="")
    except:
        raise UserHTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
                                retcode=401, rtmsg="Authentication Error.", data="")
    if not (await SessionManager.verify_user(session_id)):
        raise UserHTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
                                retcode=401, rtmsg="Authentication Error.", data="")


async def get_user_sub(request: HTTPConnection) -> uuid:
    """从Session中获取用户"""
    # if config["DEBUG"]:
    #     await UserManager.add_user((await Convertor.convert_user_sub_to_user_entity('admin')))
    #     return "admin"
    try:
        session_id = None
        auth_header = request.headers.get("Authorization")
        if auth_header and auth_header.startswith("Bearer "):
            session_id = auth_header.split(" ", 1)[1]
        elif "ECSESSION" in request.cookies:
            session_id = request.cookies["ECSESSION"]
    except:
        raise UserHTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
                                retcode=401, rtmsg="Authentication Error.", data="")
    user_sub = await SessionManager.get_user_sub(session_id)
    if not user_sub:
        raise UserHTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
                                retcode=401, rtmsg="Authentication Error.", data="")
    return user_sub
